package cn.itcast.bos.web.action.base;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Actions;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

import cn.itcast.bos.domain.base.Area;
import cn.itcast.bos.service.base.AreaService;
import cn.itcast.bos.utils.PinYin4jUtils;
import cn.itcast.bos.web.action.common.BaseAction;

@ParentPackage("json-default")	//继承之后可将前端传过来的查询条件字符串封装到area模型驱动中,使后面area中有数据,从而
@Namespace("/")					//使StringUtils.isNotBlank(area.getProvince)得以判断
@Actions
@Controller
@Scope("prototype")
public class AreaAction extends BaseAction<Area> {	//对于area,模型驱动只有在页面添加对象,action中获取对应对象时才能用到
	private Area area=new Area();	//模型驱动一般添加或者修改数据时将添加或者修改的对象传递到action中
	
	@Autowired
	private AreaService areaService;
	//属性驱动
	private File file;
	public void setFile(File file) {
		this.file = file;
	}

	//条件查询
	private String province;
	private String city;
	private String district;
	public void setProvince(String province) {
		this.province = province;
	}
	public void setCity(String city) {
		this.city = city;
	}
	public void setDistrict(String district) {
		this.district = district;
	}
	
	//分页查询(和条件查询共用一个方法)
	@Action(value="area_pageQuery", results={@Result(type="json")})
	public String queryPage(){
		
		//构造条件查询对象
		Specification<Area> specification=new Specification<Area>(){
			
			@Override
			public Predicate toPredicate(Root<Area> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				List<Predicate> predicates=new ArrayList<Predicate>();
				if(StringUtils.isNotBlank(model.getProvince())){	//这里的area属性里有值	???	答:上面ParentPackage继承Json-default从而实现
					Predicate p1=cb.like(root.get("province").as(String.class),"%"+model.getProvince()+"%");
					predicates.add(p1);
//					System.out.println("========================================="+p1);
				}
				if(StringUtils.isNotBlank(model.getCity())){
					Predicate p2=cb.like(root.get("city").as(String.class), "%"+model.getCity()+"%");
					predicates.add(p2);
				}
				if(StringUtils.isNotBlank(model.getDistrict())){
					Predicate p3=cb.like(root.get("district").as(String.class),"%"+model.getDistrict()+"%");
					predicates.add(p3);
				}
//				System.out.println(predicates+"==============================================================================================");
				return cb.and(predicates.toArray(new Predicate[0]));	//and代表是and的关系(同时满足),并且and后参数为可变参数,
			}};															//因此把集合predicates转换为array数组,并且定义为predicate类型
		
		
		Pageable pageable=new PageRequest(page-1,rows);
		System.out.println("pageable=============================="+pageable);
		Page<Area> pageData=areaService.findPageData(specification,pageable);
		System.out.println("pageData==============================="+pageData);
		pushPageDataToValueStack(pageData);
		return SUCCESS;
	}

	//一键导入区域数据
	@Action(value="area_batchImport")
	public String batchImport() throws IOException{
		List<Area> areas=new ArrayList<Area>();
		//编写解析代码逻辑
		//基于.xls文件格式使用HSSF解析
		//基于.xlsx使用XSSF解析
		//1.加载EXCEL文件对象
		HSSFWorkbook hssfWorkbook=new HSSFWorkbook(new FileInputStream(file));
		//2.读取一个sheet
		HSSFSheet sheet=hssfWorkbook.getSheetAt(0);
		//3.读取sheet中的每一行
		for(Row row:sheet){
			//一行数据对应一个区域对象
			if(row.getRowNum()==0){
				//第一行跳过
				continue;
			}
			if(row.getCell(0)==null || StringUtils.isBlank(row.getCell(0).getStringCellValue())){
				//单元格为空
				continue;
			}
			Area area=new Area();	//这里是为了生成对象并赋值,和模型驱动无关
			area.setId(row.getCell(0).getStringCellValue());
			area.setProvince(row.getCell(1).getStringCellValue());
			area.setCity(row.getCell(2).getStringCellValue());
			area.setDistrict(row.getCell(3).getStringCellValue());
			area.setPostcode(row.getCell(4).getStringCellValue());
			
			//使用pinyin4j生成城市编码和简码
			String province=area.getProvince();
			String city=area.getCity();
			String district=area.getDistrict();
			
			province=province.substring(0, province.length()-1);	//去掉最后一个子"省",下面两个同理
			city=city.substring(0, city.length()-1);
			district=district.substring(0, district.length()-1);
			String[] headArray = PinYin4jUtils.getHeadByString(province+city+district);
			StringBuilder sb=new StringBuilder();
			for (String headStr : headArray) {
				sb.append(headStr);
			}
			String shortcode=sb.toString();
			area.setShortcode(shortcode);
			String citycode=PinYin4jUtils.hanziToPinyin(city, "");
			area.setCitycode(citycode);
			
			areas.add(area);
		}
		//调用业务层,将数据写入到数据库中
		areaService.saveBatch(areas);
		return NONE;
	}

	//继承BaseAction后这里不再需要返回模型对象了,忘了删除会导致查询失效
	//这是写到页尾的弊端,抽取代码时容易忘记注释这里
	/*@Override
	public Area getModel() {
		return model;	
	}*/
}
